package com.erp.gather.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.erp.gather.domain.bo.ErpUsdExchangeBo;
import com.erp.gather.domain.vo.ErpUsdExchangeVo;
import com.erp.gather.service.IErpUsdExchangeService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;

import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.gather.api.domain.ErpUsdExchange;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
//TODO 采集相关 暂不迁移

/**
 * 美元汇率
 *
 * @author erp
 * @date 2023-05-06
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/gather/usdExchange")
public class ErpUsdExchangeController extends BaseController {
    @Autowired
    RestTemplate restTemplate;
    private final IErpUsdExchangeService iErpUsdExchangeService;

    /**
     * 查询最新汇率
     */
    @GetMapping("/getNewUsdExchange")
    public BigDecimal getNewUsdExchange(String code) {
        return iErpUsdExchangeService.getNewUsdExchange(code);
    }

    /**
     * 测试
     *
     * @return
     */
    @GetMapping("/getNowUsdExchange")
    public R<String> getNowUsdExchange() {
        //调用接口，获取数据
        String key = "aaa6debcf6088418aaf440ed99984f05";
        ResponseEntity<String> forEntity = restTemplate
                .getForEntity("http://web.juhe.cn/finance/exchange/rmbquot?type=&bank=&key=" + key, String.class);
        String body = (String) forEntity.getBody();
        System.out.println(body);
        //切割字符串
        String result = JSONObject.parseObject(body).getString("result");
        List<Dict> dicts = JsonUtils.parseArrayMap(result);
        for (Dict dict : dicts) {
            System.out.println(dict);
            for (int i = 1; i <= 20; i++) {
                if (!JSONObject.parseObject(JSON.toJSONString(dict.get("data" + i))).getString("name").equals("美元")) {
                    continue;
                }
                ErpUsdExchange usdExchange = JSONObject.parseObject(JSON.toJSONString(dict.get("data" + i)), ErpUsdExchange.class);
                usdExchange.setCreateTime(new Date());
                iErpUsdExchangeService.insertUsdExchange(usdExchange);
            }
        }
        return R.ok("已获取到最新汇率");
    }

    /**
     * 查询美元汇率列表
     */
    @SaCheckPermission("system:usdExchange:list")
    @GetMapping("/list")
    public TableDataInfo<ErpUsdExchangeVo> list(ErpUsdExchangeBo bo, PageQuery pageQuery) {
        return iErpUsdExchangeService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取美元汇率详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:usdExchange:query")
    @GetMapping("/{id}")
    public R<ErpUsdExchangeVo> getInfo(@NotNull(message = "主键不能为空")
                                       @PathVariable Long id) {
        return R.ok(iErpUsdExchangeService.queryById(id));
    }

    /**
     * 新增美元汇率
     */
    @SaCheckPermission("system:usdExchange:add")
    @Log(title = "美元汇率", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ErpUsdExchangeBo bo) {
        return toAjax(iErpUsdExchangeService.insertByBo(bo));
    }

    /**
     * 修改美元汇率
     */
    @SaCheckPermission("system:usdExchange:edit")
    @Log(title = "美元汇率", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpUsdExchangeBo bo) {
        return toAjax(iErpUsdExchangeService.updateByBo(bo));
    }

    /**
     * 删除美元汇率
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:usdExchange:remove")
    @Log(title = "美元汇率", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iErpUsdExchangeService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 根据时间获取汇率
     * @param time 时间
     * @param currencyCode 币种
     * @return 汇率
     */
    @GetMapping("/getExchangeByTime/{time}/{currencyCode}")
    public R<Object> getExchangeByTime(@PathVariable String time, @PathVariable String currencyCode){
        return R.ok(iErpUsdExchangeService.getExchangeByTime(time, currencyCode));
    }
}
